package com.xysq.activity;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.widget.Toast;

import com.rockcent.action.CallbackListener;
import com.xysq.lemon.R;
import com.xysq.util.ToastUtil;
import com.xysq.util.UserInfoKeeper;

/**
 * Copyright (c) 2015 XiaoYuanShenQi. All rights reserved.
 * <p/>
 * Author: Dengqi
 * Date: 2015-7-13
 * Description: XYShakeActivity
 */

public class ShakeActivity extends BaseActivity {

    private SensorManager sensorManager;
    private Vibrator vibrator;

    private static final String TAG = "TestSensorActivity";
    private static final int SENSOR_SHAKE = 1;
    private int shakeCount = 0;
    private long firstShakeTime = 0;
    private static final long MAX_INTERVAL_TIME = 1500;
    private static final long MIN_INTERVAL_TIME = 300;
    private static final int MEDUM_VALUE = 15;
    private static final int VIBRATE_VALUE = 200;

    private boolean isShakeTwice() {
        shakeCount = shakeCount + 1;
        if (shakeCount == 1) {
            firstShakeTime = System.currentTimeMillis();
            return false;
        }
        if (shakeCount == 2) {
            long sencondShakeTime = System.currentTimeMillis();
            long intervalTime = sencondShakeTime - firstShakeTime;
            if ((intervalTime < MAX_INTERVAL_TIME) && (intervalTime > MIN_INTERVAL_TIME)) {
                return true;
            } else {
                firstShakeTime = sencondShakeTime;
                return false;
            }
        }
        return false;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shake);
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (sensorManager != null) {// 注册监听器
            sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
            // 第一个参数是Listener，第二个参数是所得传感器类型，第三个参数值获取传感器信息的频率
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (sensorManager != null) {// 取消监听器
            sensorManager.unregisterListener(sensorEventListener);
        }
    }

    /**
     * 重力感应监听
     */
    private SensorEventListener sensorEventListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {

            // 传感器信息改变时执行该方法
            float[] values = event.values;
            float x = values[0]; // x轴方向的重力加速度，向右为正
            float y = values[1]; // y轴方向的重力加速度，向前为正
            float z = values[2]; // z轴方向的重力加速度，向上为正

//            Log.i(TAG, "x" + x + "；y" + y + "；z" + z);
            // 一般在这三个方向的重力加速度达到40就达到了摇晃手机的状态。
            int medumValue = MEDUM_VALUE;// 阈值。
            Log.d("test", Math.abs(x) + "x");
            Log.d("test", Math.abs(y) + "y");
            Log.d("test", Math.abs(z) + "z");
            if (Math.abs(x) > medumValue || Math.abs(y) > medumValue || Math.abs(z) > medumValue) {
                if (isShakeTwice()) {
                    shakeCount = 0;
                    vibrator.vibrate(VIBRATE_VALUE);
                    Message msg = new Message();
                    msg.what = SENSOR_SHAKE;
                    handler.sendMessage(msg);

/*                    Bundle bundle = new Bundle();
                    bundle.putSerializable("myXyMarketItem", new XYMarketItem());
                    Intent intent = new Intent(ShakeActivity.this, GoodsDetailActivity.class);
                    intent.putExtras(bundle);
                    startActivity(intent);*/
                }
            } else {

                shakeCount = 1;
                System.out.println("no result");

            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    /**
     * 动作执行
     */
    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SENSOR_SHAKE:
                    Toast.makeText(ShakeActivity.this, "检测到摇晃，执行操作！", Toast.LENGTH_SHORT).show();
                    Log.i(TAG, "检测到摇晃，执行操作！");
                    getData();
                    break;
            }
        }
    };

    private void getData() {
        appAction.createCouponPackageOrder(UserInfoKeeper.readPhoneNumber(ShakeActivity.this), "1", new CallbackListener<String>() {
            @Override
            public void onSuccess(String data) {
                ToastUtil.showLong(ShakeActivity.this, data);
            }

            @Override
            public void onFailure(String errorEvent, String message) {
                ToastUtil.showShort(ShakeActivity.this, message);
            }
        });
    }
}